package net.wanho.warehouse.interceptor;

import net.wanho.warehouse.contant.UserConstant;
import net.wanho.warehouse.util.CurrentUtil;
import net.wanho.warehouse.util.JwtUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getRequestURI());
        /**
         * 获取请求头中的token，如果有，表示已登录，则放行
         */
        String token = request.getHeader("Authorization");
        if (StringUtils.isEmpty(token)){
            throw new RuntimeException("请先登录再操作！");
        }

        token = token.replace("Bearer ", "");
        if(!JwtUtil.verify(token)){
            throw new RuntimeException("token无效，请重新登录！");
        }

        // 获取用户id和username
        Integer id = JwtUtil.parseInteger(token, UserConstant.USER_ID);
        CurrentUtil.setId(id);

        return true; // 放行
    }
}
